package club.lemos.textdrawer;


import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

import static java.awt.Image.SCALE_SMOOTH;

public class ImagePanel extends JPanel {

    private final BufferedImage image;

    public ImagePanel(BufferedImage image) {
        this.image = image;
    }

    // 按比例缩放
    private Image getScaledImage() {
        int panelWidth = getWidth();
        int panelHeight = getHeight();
        int imageWidth = this.image.getWidth();
        int imageHeight = this.image.getHeight();
        double ratio = 1.0;
        if (imageWidth > panelWidth) {
            ratio = panelWidth * 1.0 / imageWidth;
            if (imageHeight * ratio > panelHeight) {
                ratio = ratio * panelHeight / (imageHeight * ratio);
            }
        } else if (imageHeight > panelHeight) {
            ratio = panelHeight * 1.0 / imageHeight;
            if (imageWidth * ratio > panelWidth) {
                ratio = ratio * panelWidth / (imageWidth * ratio);
            }
        }
        return this.image.getScaledInstance((int) (imageWidth * ratio), (int) (imageHeight * ratio), SCALE_SMOOTH);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Image scaledImage = getScaledImage();
        int x = (getWidth() - scaledImage.getWidth(this)) / 2;
        int y = (getHeight() - scaledImage.getHeight(this)) / 2;
        g.drawImage(scaledImage, x, y, this);
    }

}
